import { defineStore } from 'pinia'
import { getStorage, setStorage } from '@/utils/storage'

interface TagView {
  fullPath: string
  path: string
  query: Record<string, any>
  title?: string
  meta?: {
    affix?: boolean
    noCache?: boolean
    name?:String
    noTagsView?: boolean
    [key: string]: any

  }
}

export const useTagsViewStore = defineStore('tagsView', {
  state: () => ({
    visitedViews: getStorage<TagView[]>('visitedViews') || [],
    cachedViews: getStorage<string[]>('cachedViews') || []
  }),

  actions: {
    addView(view: TagView) {
      if (view.meta?.noTagsView) return
      const index = this.visitedViews.findIndex(v => v.path === view.path)
      if (index === -1) {
        this.visitedViews.push({
          fullPath: view.fullPath,
          path: view.path,
          query: view.query || {},
          title: view.meta?.title || 'unknown',
          meta: { ...view.meta }
        })
        if (!view.meta?.noCache && view.title) {
          this.cachedViews.push(view.meta?.name as string)
        }
        setStorage('visitedViews', this.visitedViews)
        setStorage('cachedViews', this.cachedViews)
      }
    },

    delView(view: TagView) {
      return new Promise<TagView[]>(resolve => {
        this.visitedViews = this.visitedViews.filter(v => v.path !== view.path)
        this.cachedViews = this.cachedViews.filter(v => v !== view.meta?.name )
        setStorage('visitedViews', this.visitedViews)
        setStorage('cachedViews', this.cachedViews)
        resolve([...this.visitedViews])
      })
    },

    isActive(view: TagView): boolean {
      return this.$state.visitedViews.some(v => v.fullPath === view.fullPath)
    },

    // 其他操作方法需要补充类型
    delOthersViews(view: TagView) {
      /* 实现 */
    },

    delLeftViews(view: TagView) {
      /* 实现 */
    },

    delRightViews(view: TagView) {
      /* 实现 */
    },

    delAllViews() {
      /* 实现 */
    },

    initAffixTags(route: TagView) {
      /* 实现 */
    }
  }
})
